#include <stdlib.h>
#include <stdio.h>

#include "player.h"
#include "units.h"

// Helper pour init_player
void load_data(SPlayer * player, SMap * world, int idTeam);

SPlayer * init_player(SMap * world, int idTeam) {
	SPlayer * player = malloc(sizeof(SPlayer));
	
	if (player) {
		player->idTeam = idTeam;
		player->units = v_new(10);
		load_data(player, world, idTeam);
	} else {
		exit(fprintf(stderr, "In init_player : failed to allocate memory.\n"));
	}
	
	return player;
}

void pAddUnit(SPlayer * player, SMap * world, SUnit unit) {
	// Mise a jour du joueur
	STroup * troup = new_troup(unit.idCell, player->idTeam, v_count(player->units) + 1, unit.type);
	v_add(player->units, *troup);
	
	// Mise a jour de la map
	world->map[unit.idCell-1].idTeam = troup->idTeam;
	world->map[unit.idCell-1].idUnit = troup->idUnit;
	world->map[unit.idCell-1].u_type = troup->u_type;
	
	free(troup);
}

void free_player(SPlayer * player) {
	v_delete(player->units);
	free(player);
}

void print_player(SPlayer * player) {
	printf("Player : %d\n-----------\n", player->idTeam);
	printf("Units : (idUnit, idCell, type)\n[ ");
	for (int i = 0; i < v_count(player->units); i++) {
		STroup t = v_get(player->units, i);
		print_unit(&t);
	}
	printf("]\n");
}

void load_data(SPlayer * player, SMap * world, int idTeam) {
	for (int i = 0; i < world->size; i++) {
		if (world->map[i].idTeam == idTeam) {
			SUnit unit;
			unit.idCell = world->map[i].cell.idCell;
			unit.type = world->map[i].u_type;
			
			pAddUnit(player, world, unit);
		}
	}
}